package com.sitech.webapp.listener;

import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sitech.context.SpringContext;
import com.sitech.server.Server;
import com.sitech.server.ServerStart;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * <p>
 * StartupListener class used to initialize and database settings and populate
 * any application-wide drop-downs. <p/>
 * <p>
 * Keep in mind that this listener is executed outside of
 * OpenSessionInViewFilter, so if you're using Hibernate you'll have to
 * explicitly initialize all loaded data at the GenericDao or service level to
 * avoid LazyInitializationException. Hibernate.initialize() works well for
 * doing this.
 * 
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
public class StartupListener implements ServletContextListener
{
	private static final Log log = LogFactory.getLog(StartupListener.class);

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public void contextInitialized(ServletContextEvent event)
	{
		log.debug("Initializing context...");

		ServletContext context = event.getServletContext();

		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

		setupContext(context);
		SpringContext.initialize(context);

		try
		{
			System.out.println("server start begin.");
			Map<String, ServerStart> map = ctx.getBeansOfType(ServerStart.class);
			if (map != null && map.size() > 0)
			{
				TreeMap<Integer , ServerStart> treeMap = new TreeMap<Integer, ServerStart>();
				
				for (Map.Entry<String, ServerStart> entry : map.entrySet())
				{
					ServerStart serverStart = entry.getValue();
					treeMap.put(serverStart.getOrderNo(), serverStart);			
				}
				
				for(Map.Entry<Integer, ServerStart> entry : treeMap.entrySet())
				{
					ServerStart serverStart = entry.getValue();
					serverStart.start(context);
				}
			}
			System.out.println("server start end.");
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.out.println("No Server Config!");
		}
	}

	/**
	 * This method uses the LookupManager to lookup available roles from the
	 * data layer.
	 * 
	 * @param context
	 *            The servlet context
	 */
	public static void setupContext(ServletContext context)
	{
		log.debug("Drop-down initialization complete [OK]");
	}

	/**
	 * Shutdown servlet context (currently a no-op method).
	 * 
	 * @param servletContextEvent
	 *            The servlet context event
	 */
	public void contextDestroyed(ServletContextEvent servletContextEvent)
	{

	}
}
